﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace BoarAccess
{
    public class SessionInfo
    {
        public int ID, ParentID;
        public DateTime Timestamp;
        public string Message, Name, InfoFilename;

        private Dictionary<string, FileInfo> files;

        internal SessionInfo(int id, string filename)
        {
            JObject currentSession = JObject.Parse(LocalSession.resources.RetrieveFileResource(filename));
            this.ID = id;
            try
            {
                this.ParentID = (int)currentSession["base_session"];
            }
            catch
            {
                this.ParentID = -1;
            }
            
            this.Timestamp = ResourceManager.FromUnix((long)currentSession["client_data"]["timestamp"]);
            this.Message = (string)currentSession["client_data"]["log_message"];
            this.Name = (string)currentSession["client_data"]["name"];
            this.InfoFilename = filename;
        }

        public override string ToString()
        {
            return "Session " + this.ID + ": " + Message + " (" + this.Timestamp.ToShortDateString() + ")";
        }

        public SessionInfo ParentSession
        {
            get
            {
                try
                {
                    var p = Path.GetDirectoryName(this.InfoFilename);
                    var d = Directory.GetParent(p);
                    return new SessionInfo(this.ParentID, d + "\\" + this.ParentID + "\\session.json");
                }
                catch
                {
                    return null;
                }
            }
        }

        private void initFilesCollection()
        {
            if (files == null)
                files = new Dictionary<string, FileInfo>();
            var temp = FileInfo.LoadFromJSON(this.InfoFilename.Replace("session.json", "bloblist.json"), this);
            foreach (var item in temp)
            {
                files.Add(item.Filename, item);
            }
        }

        public IEnumerable<FileInfo> Files
        {
            get
            {
                if (this.files == null)
                {
                    initFilesCollection();
                }
                return files.Values;
            }
        }

        public FileInfo RetrieveFileInfo(string filename)
        {
            if (this.files == null)
            {
                initFilesCollection();
            }
            if (files.ContainsKey(filename.Replace("\\", "/")))
                return files[filename.Replace("\\", "/")];
            else
                return null;
        }
    }
}
